<template>
  <div class="flex flex-col">
    <div class="b-title">{{ props.title || "" }}</div>
    <div ref="boxRef" class="flex-1 border-box p-24">
      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        :height="height"
        row-class-name="kb-tr"
        header-row-class-name="kb-th"
        @mouseenter="autoScroll(true)"
        @mouseleave="autoScroll(false)"
      >
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          align="center"
        >
          <template #header>
            <div class="font-14">{{ item.label }}</div>
          </template>
          <template #default="scope">
            <div class="font-14">
              {{
                item.formatter
                  ? item.formatter(scope.row)
                  : scope.row[item.prop]
              }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="ts" scoped setup>
import { realWH } from "@/utils";
import { computed, onMounted, ref, onBeforeUnmount, watch } from "vue";

const props = defineProps({
  data: {
    default: () => []
  },
  title: {
    default: "",
    type: String
  },
  height: {
    type: [String, Number],
    default: 100
  },
  columns: {
    type: Array,
    default: () => []
  }
});
/* 数据 */
const columns = computed(() => [...props.columns] as any);
const tableData = ref(props.data);

/* 高度 */
const boxRef = ref();
const height = ref(props.height);
onMounted(() => {
  height.value = boxRef.value.offsetHeight - realWH(40).w;
});

/* 自动滚动 */
let scrolltimer = null;
const tableRef = ref(null);

// 是否有滚动
const firstInit = ref(true);
const autoScroll = (stop = false) => {
  if (!tableData.value.length) return false;
  const tableBody = tableRef.value.$refs.bodyWrapper;
  const divData = tableBody.getElementsByClassName("el-scrollbar__wrap")[0];
  if (divData.scrollHeight <= divData.clientHeight) {
    return false;
  } else if (firstInit.value) {
    const temp = tableData.value.slice(0, 10);
    tableData.value.push(...temp);
  }
  firstInit.value = false;
  if (stop) {
    window.clearInterval(scrolltimer);
  } else {
    const step = 3;
    let scrollTop = divData.scrollTop;
    scrolltimer = window.setInterval(() => {
      if (scrollTop >= divData.scrollHeight / 2) {
        scrollTop = 0;
      } else {
        scrollTop += step;
      }
      divData.scrollTop = scrollTop;
    }, 150);
  }
};
onMounted(() => {
  setTimeout(() => {
    autoScroll();
  }, 1000);
});
onBeforeUnmount(() => {
  autoScroll(true);
});
</script>

<style lang="scss" scoped>
@import url(../table.scss);
</style>
